const cors = require('koa2-cors');
var Koa = require("koa");
var Router = require("koa-router");
var fs = require("fs");
var bodyParser = require("koa-body");
const con = require('./api/con');



//const multipart = require('koa-multipart');
var app = new Koa();
var router = new Router();
app.use(bodyParser({
  enableTypes: ['json','form','text'],
  multipart: true
}));
//app.use(multipart());

app.use(cors({
  origin: function (ctx) {
    if(ctx.url === '/upshop' || ctx.url === '/changesp'){
      return "*";
    }
    return 'http://localhost:8080';
  },
  exposeHeaders: ['WWW-Authenticate','Server-Authorization'],
  maxAge: 5,
  credentials: true,
  allowMethods: ['GET','POST','DELETE'],
  allowHeaders: ['Content-Type','Authorization','Accept'],
}))

//获取最大id
var id1;
async function getMd(){
  const sql = `select max(id) id from shop_table`;
  let [rows] = await con.execute(sql);
  return rows;
}

(async function(){
  id1 = (await getMd())[0].id + 1;
})();

router.post("/upshop", async (ctx, next) => {
  //已有id1
  var shopname1 = ctx.request.body.shopname;
  var shopaddr1 = ctx.request.body.shopaddr;
  var shop_img1 = `/shop/${id1}/image.png`;
  var shopscount1 = ctx.request.body.shopscount;
  var shoplabel1 = ctx.request.body.shoplabel;
  var shopmtid1 = ctx.request.body.shopmid;
  var shoptel1 = ctx.request.body.shoptel;
  var shopwm1  = ctx.request.body.shopwm;
  var shopjwd = ctx.request.body.shopjw;
  var shopcount1 = ctx.request.body.shopcount;
  var spdis1 = ctx.request.body.shopdistribution1;
  var spdis2 = ctx.request.body.shopdistribution2;
  var spduc1 = ctx.request.body.shopreduction1;
  var spduc2 = ctx.request.body.shopreduction2;
  var spduc3 = ctx.request.body.shopreduction3;



  //插入商家数据
  async function insertSP(){
    const sql = `INSERT INTO shop_table (id, shop_name, shop_img, shop_tel, shop_addr, shop_jwd, shop_mtid, shop_label, shop_starcount, shop_count, shop_distribution1, shop_distribution2, shop_reduction1, shop_reduction2, shop_reduction3, shop_announcementinfo) VALUES ('${id1}', '${shopname1}', '${shop_img1}', '${shoptel1}', '${shopaddr1}', '${shopjwd}', '${shopmtid1}', '${shoplabel1}', '${shopscount1}', '${shopcount1}', '${spdis1}' ,'${spdis2}', '${spduc1}', '${spduc2}', '${spduc3}', '${shopwm1}')`;
    let [rows] = await con.execute(sql);
    return rows;
  }
  (async function(){
    await insertSP();
  })();

  var imgData = ctx.request.body.shopimg;
  var base64Data = imgData.replace(/^data:image\/\w+;base64,/, "");
  var dataBuffer = Buffer.from(base64Data, 'base64');

  try{
    if(fs.existsSync(`shop/${id1}`)){
      console.log("文件夹存在");
      fs.writeFile(`./shop/${id1}/image.png`, dataBuffer, function(err) {
        if(err){
          ctx.body = err;
        }else{
        ctx.body = JSON.stringify('success');
        }
      });
    }else{
      console.log("文件夹不存在");
      fs.mkdirSync(`shop/${id1}`,app.callback());
      fs.writeFile(`./shop/${id1}/image.png`, dataBuffer, function(err) {
        if(err){
          ctx.body = err;
        }else{
          ctx.body = JSON.stringify('success');
        }
      });
    }
  }catch(e){
    console.log(e);
  }


  //console.log(id1);
  //console.log(ctx.request.body.shopname);
  fs.writeFile(`./shop/${id1}/image.png`, dataBuffer, function(err) {
    if(err){
      ctx.body = err;
    }else{
      ctx.body = JSON.stringify('success');
    }
  });
  id1++;
  ctx.body = JSON.stringify('success');
});


router.post('/changesp',async (ctx) => {
  //console.log(ctx.request.body.id);
  var id2 = ctx.request.body.id;
  var shopname1 = ctx.request.body.shopname;
  var shopaddr1 = ctx.request.body.shopaddr;
  var shop_img1 = `/shop/${id2}/image.png`;
  var shopscount1 = ctx.request.body.shopscount;
  var shoplabel1 = ctx.request.body.shoplabel;
  var shopmtid1 = ctx.request.body.shopmid;
  var shoptel1 = ctx.request.body.shoptel;
  var shopwm1  = ctx.request.body.shopwm;
  var shopjwd = ctx.request.body.shopjw;
  var shopcount1 = ctx.request.body.shopcount;
  var spdis1 = ctx.request.body.shopdistribution1;
  var spdis2 = ctx.request.body.shopdistribution2;
  var spduc1 = ctx.request.body.shopreduction1;
  var spduc2 = ctx.request.body.shopreduction2;
  var spduc3 = ctx.request.body.shopreduction3;

  async function changeSP(){
    const sql2 = `UPDATE shop_table SET shop_name = '${shopname1}', shop_img = '${shop_img1}', shop_tel = '${shoptel1}', shop_addr = '${shopaddr1}', shop_jwd = '${shopjwd}', shop_mtid = '${shopmtid1}', shop_label = '${shoplabel1}', shop_starcount = '${shopscount1}', shop_count = '${shopcount1}', shop_distribution1 = '${spdis1}', shop_distribution2 = '${spdis2}', shop_reduction1 = '${spduc1}', shop_reduction2 = '${spduc2}', shop_reduction3 = '${spduc3}', shop_announcementinfo = '${shopwm1}' where (id = '${id2}')`;
    let [rows] = await con.execute(sql2);
    return rows;
  }
  (async function(){
    await changeSP();
  })();

  //差个传图片
  var imgData1 = ctx.request.body.shopimg;
  var base64Data1 = imgData1.replace(/^data:image\/\w+;base64,/, "");
  var dataBuffer1 = Buffer.from(base64Data1, 'base64');
  fs.writeFile(`./shop/${id2}/image.png`, dataBuffer1, function(err) {
    if(err){
      ctx.body = err;
    }else{
      ctx.body = JSON.stringify('success');
    }
  });
  
  ctx.body = JSON.stringify('success');

})



app.use(router.routes())
   .use(router.allowedMethods());

app.listen(3006);

console.log("server started at http:localhost:3006");
